import React, { useState, useEffect } from 'react';
import {
  View,
  Text,
  StyleSheet,
  TouchableOpacity,
  Dimensions,
  Alert,
  StatusBar,
  useTVEventHandler,
} from 'react-native';
import { useNavigation, useRoute, RouteProp } from '@react-navigation/native';
import { Card, ServerInfo } from '../types/Card';
import CardView from '../components/CardView';
import AudioService from '../services/AudioService';
import DatabaseService from '../services/DatabaseService';
import { RootStackParamList } from '../../App';

const { width, height } = Dimensions.get('window');

type CardDetailScreenRouteProp = RouteProp<RootStackParamList, 'CardDetail'>;

const CardDetailScreen: React.FC = () => {
  const navigation = useNavigation();
  const route = useRoute<CardDetailScreenRouteProp>();
  const { card, isLocal = false, serverInfo, cardList = [], currentIndex = 0, showCardImages = true } = route.params;
  const [isFlipped, setIsFlipped] = useState(false);
  const [currentCardIndex, setCurrentCardIndex] = useState(currentIndex);
  const [currentCard, setCurrentCard] = useState(card);
  const [isPlaying, setIsPlaying] = useState(false);
  const [isLoadingAudio, setIsLoadingAudio] = useState(false);
  const [isDownloading, setIsDownloading] = useState(false);
  const [localCard, setLocalCard] = useState<Card | null>(null);
  const [showUpdateButton, setShowUpdateButton] = useState(false);
  const [currentShowCardImages, setCurrentShowCardImages] = useState(showCardImages); // 添加显示模式状态

  // 检查本地卡片状态
  const checkLocalCard = async () => {
    console.log('🔍 开始检查本地卡片...');
    console.log('📱 当前卡片信息:', {
      isLocal,
      uuid: currentCard.uuid,
      updated_at: currentCard.updated_at,
      title: currentCard.title,
      front_image: currentCard.front_image,
      back_text: currentCard.back_text,
      audio_path: currentCard.audio_path
    });
    
    if (!isLocal && currentCard.uuid) {
      try {
        const localCards = await DatabaseService.getLocalCards();
        console.log('📋 本地卡片列表:', localCards.map(c => ({ 
          id: c.id, 
          uuid: c.uuid, 
          title: c.title, 
          updated_at: c.updated_at,
          front_image: c.front_image,
          back_text: c.back_text,
          audio_path: c.audio_path
        })));
        
        const foundCard = localCards.find(localCard => localCard.uuid === currentCard.uuid);
        console.log('🎯 找到的匹配卡片:', foundCard ? {
          id: foundCard.id,
          uuid: foundCard.uuid,
          title: foundCard.title,
          updated_at: foundCard.updated_at,
          front_image: foundCard.front_image,
          back_text: foundCard.back_text,
          audio_path: foundCard.audio_path
        } : null);
        
        if (foundCard) {
          console.log('✅ 设置本地卡片:', foundCard);
          setLocalCard(foundCard);
          
          // 比较更新时间
          const localUpdatedAt = foundCard.updated_at;
          const remoteUpdatedAt = currentCard.updated_at;
          const needsUpdate = localUpdatedAt !== currentCard.updated_at;
          
          console.log('⏰ 详细时间比较:', {
            localUpdatedAt,
            remoteUpdatedAt,
            localUpdatedAtType: typeof localUpdatedAt,
            remoteUpdatedAtType: typeof remoteUpdatedAt,
            localUpdatedAtLength: localUpdatedAt ? localUpdatedAt.length : 0,
            remoteUpdatedAtLength: remoteUpdatedAt ? remoteUpdatedAt.length : 0,
            needsUpdate,
            isEqual: localUpdatedAt === remoteUpdatedAt,
            isStrictEqual: localUpdatedAt === remoteUpdatedAt
          });
          
          console.log('🔄 设置更新按钮状态:', needsUpdate);
          setShowUpdateButton(needsUpdate);
        } else {
          console.log('❌ 未找到匹配的本地卡片');
          setLocalCard(null);
          setShowUpdateButton(false);
        }
      } catch (error) {
        console.error('❌ 检查本地卡片失败:', error);
      }
    } else {
      console.log('⏭️ 跳过检查:', { isLocal, hasUuid: !!currentCard.uuid });
    }
  };

  const handleFlip = () => {
    setIsFlipped(!isFlipped);
  };

  const handleToggleDisplay = () => {
    setCurrentShowCardImages(!currentShowCardImages);
    console.log(`🖼️ CardDetailScreen 切换到${!currentShowCardImages ? '图片' : '文字'}显示`);
  };

  const handlePrevious = () => {
    if (cardList.length > 1) {
      const newIndex = (currentCardIndex - 1 + cardList.length) % cardList.length;
      setCurrentCardIndex(newIndex);
      setCurrentCard(cardList[newIndex]);
      setIsFlipped(false);
    }
  };

  const handleNext = () => {
    if (cardList.length > 1) {
      const newIndex = (currentCardIndex + 1) % cardList.length;
      setCurrentCardIndex(newIndex);
      setCurrentCard(cardList[newIndex]);
      setIsFlipped(false);
    }
  };

  const handleBack = () => {
    navigation.goBack();
  };

  const handleRead = async () => {
    if (!currentCard.audio_path) {
      Alert.alert('朗读', '此卡片没有音频内容');
      return;
    }

    try {
      if (isPlaying) {
        // 如果正在播放，停止播放
        await AudioService.stopAudio();
        setIsPlaying(false);
      } else {
        // 开始播放
        setIsLoadingAudio(true);
        await AudioService.playAudio(currentCard.audio_path, serverInfo);
        setIsPlaying(true);
      }
    } catch (error) {
      console.error('音频播放失败:', error);
      Alert.alert('播放失败', '音频播放失败，请重试');
    } finally {
      setIsLoadingAudio(false);
    }
  };

  const handleDownload = async () => {
    if (isDownloading) return;
    
    setIsDownloading(true);
    try {
      const cardData = {
        title: currentCard.title,
        front_image: currentCard.front_image,
        back_text: currentCard.back_text,
        audio_path: currentCard.audio_path,
        uuid: currentCard.uuid,
        created_at: currentCard.created_at,
        updated_at: currentCard.updated_at,
      };
      
      const result = await DatabaseService.saveCard(cardData, serverInfo);
      console.log('✅ 下载成功:', result);
      
      // 下载成功后，重新检查本地卡片状态
      await checkLocalCard();
    } catch (error: any) {
      console.error('❌ 下载失败:', error);
      if (error.code === 'CARD_EXISTS') {
        Alert.alert('提示', '卡片已存在，无需重复下载');
      } else {
        Alert.alert('下载失败', error.message || '保存卡片失败，请重试');
      }
    } finally {
      setIsDownloading(false);
    }
  };

  const handleDelete = async () => {
    if (!isLocal || !currentCard.id) {
      Alert.alert('提示', '只能删除本机数据');
      return;
    }

    Alert.alert(
      '确认删除',
      `确定要删除卡片"${currentCard.title}"吗？此操作不可撤销。`,
      [
        { text: '取消', style: 'cancel' },
        {
          text: '删除',
          style: 'destructive',
          onPress: async () => {
            try {
              const result = await DatabaseService.deleteCard(currentCard.id);
              Alert.alert('成功', result.message, [
                { text: '确定', onPress: () => navigation.goBack() }
              ]);
            } catch (error: any) {
              Alert.alert('错误', error.message || '删除失败，请重试');
            }
          }
        }
      ]
    );
  };

  // 检查本地是否有相同UUID的卡片
  useEffect(() => {
    checkLocalCard();
  }, [currentCard.uuid, currentCard.updated_at, isLocal]);

  // 组件卸载时停止音频播放
  useEffect(() => {
    return () => {
      AudioService.stopAudio().catch(console.error);
    };
  }, []);

  return (
    <View style={styles.container}>
      <StatusBar hidden={true} />
      
      {/* 使用 CardView 组件 */}
      <CardView
        card={currentCard}
        onFlip={handleFlip}
        onNext={handleNext}
        onPrevious={handlePrevious}
        onBack={handleBack}
        onRead={handleRead}
        onDownload={handleDownload}
        onDelete={handleDelete}
        onToggleDisplay={handleToggleDisplay}
        serverInfo={serverInfo}
        isLocal={isLocal}
        isDownloading={isDownloading}
        isPlaying={isPlaying}
        isLoadingAudio={isLoadingAudio}
        localCard={localCard}
        showUpdateButton={showUpdateButton}
        showCardImages={currentShowCardImages}
      />
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#1a1a1a',
  },
});

export default CardDetailScreen; 